<!--
 * @Author: 冕上 cxm66888@163.com
 * @Date: 2025-01-01 00:00:00
 * @LastEditors: 冕上 cxm66888@163.com
 * @LastEditTime: 2025-08-15 23:10:52
 * @Description: 兑换记录
 * 
 * Copyright (c) 2025 by xiaoMing.Cao, All Rights Reserved. 
-->
<template>
  <div class="app-container">
    <!-- 搜索筛选区域 -->
    <el-card class="filter-container" shadow="never">
      <el-form :model="listQuery" :inline="true" class="filter-form">
        <el-form-item label="用户昵称">
          <el-input v-model="listQuery.userName" placeholder="请输入用户昵称" style="width: 200px" clearable @keyup.enter="handleFilter" />
        </el-form-item>

        <el-form-item label="礼品名称">
          <el-input v-model="listQuery.giftName" placeholder="请输入礼品名称" style="width: 200px" clearable @keyup.enter="handleFilter" />
        </el-form-item>

        <el-form-item label="礼品类型">
          <el-select v-model="listQuery.giftType" placeholder="请选择礼品类型" style="width: 150px" clearable>
            <el-option label="VIP会员" value="vip" />
            <el-option label="实物礼品" value="real" />
            <el-option label="头饰装扮" value="headwear" />
          </el-select>
        </el-form-item>

        <el-form-item label="兑换状态">
          <el-select v-model="listQuery.status" placeholder="请选择状态" style="width: 150px" clearable>
            <el-option label="待处理" value="pending" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>

        <el-form-item label="兑换时间">
          <el-date-picker v-model="dateRange" type="datetimerange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" style="width: 350px" @change="handleDateChange" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleFilter">搜索</el-button>
          <el-button type="warning" icon="Refresh" @click="handleRefresh">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据统计卡片 -->
    <el-row :gutter="20" style="margin-bottom: 20px">
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-number">{{ statistics.total || 0 }}</div>
            <div class="stat-label">总兑换数</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-number pending">{{ statistics.pending || 0 }}</div>
            <div class="stat-label">待处理</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-number completed">{{ statistics.completed || 0 }}</div>
            <div class="stat-label">已完成</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-content">
            <div class="stat-number cancelled">{{ statistics.cancelled || 0 }}</div>
            <div class="stat-label">已取消</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 操作按钮区域 -->
    <div class="table-operations">
      <!-- <el-button type="primary" icon="Download" @click="handleExport">导出数据</el-button> -->
    </div>

    <!-- 数据表格 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="Loading..." border fit highlight-current-row>
      <el-table-column align="center" type="index" label="序号" width="80">
        <template #default="scope">
          {{ (listQuery.pageIndex - 1) * listQuery.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>

      <el-table-column label="用户信息" align="center" min-width="150">
        <template #default="scope">
          <div class="user-info">
            <div class="user-avatar">
              <el-avatar :size="40">
                {{ scope.row.userName?.charAt(0) }}
              </el-avatar>
            </div>
            <div class="user-details">
              <div class="user-name">{{ scope.row.userName }}</div>
              <div class="user-id">ID: {{ scope.row.userId }}</div>
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="礼品信息" align="center" min-width="200">
        <template #default="scope">
          <div class="gift-info">
            <el-image :src="scope.row.giftImage" style="width: 50px; height: 50px; margin-right: 12px" fit="cover" :z-index="99999" preview-teleported :preview-src-list="[scope.row.giftImage]" />
            <div class="gift-details">
              <div class="gift-name">{{ scope.row.giftName }}</div>
              <div class="gift-type">
                <el-tag :type="getGiftTypeTagType(scope.row.giftType)" size="small">
                  {{ getGiftTypeText(scope.row.giftType) }}
                </el-tag>
              </div>
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="兑换时间" align="center" width="180">
        <template #default="scope">
          <div class="time-info">
            <div>{{ formatDateTime(scope.row.createdTime) }}</div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="消耗金币" align="center" width="120">
        <template #default="scope">
          <span class="coin-text">{{ scope.row.coins }}</span>
        </template>
      </el-table-column>

      <el-table-column label="补差金额" align="center" width="120">
        <template #default="scope">
          <span v-if="scope.row.price > 0" class="amount-text">¥{{ scope.row.price }}</span>
          <span v-else class="no-amount">-</span>
        </template>
      </el-table-column>

      <el-table-column label="状态" align="center" width="120">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="数量" align="center" width="100">
        <template #default="scope">
          <span class="quantity-text">{{ scope.row.quantity || 1 }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="200" fixed="right">
        <template #default="scope">
          <el-button v-if="scope.row.status === 'pending'" type="success" size="small" @click="handleComplete(scope.row)">完成</el-button>
          <el-button type="primary" size="small" @click="handleDetail(scope.row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      style="margin-top: 20px; text-align: right"
      :current-page="listQuery.pageIndex"
      :page-size="listQuery.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      @current-change="handlePageChange"
      @size-change="handleSizeChange"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    />

    <!-- 完成兑换对话框 -->
    <el-dialog v-model="completeDialogVisible" title="完成兑换" width="500px">
      <el-form :model="completeForm" label-width="100px" :rules="completeRules" ref="completeFormRef">
        <el-form-item label="礼品类型">
          <el-tag :type="getGiftTypeTagType(completeForm.giftType)" size="small">
            {{ getGiftTypeText(completeForm.giftType) }}
          </el-tag>
        </el-form-item>

        <el-form-item label="物流公司" prop="logisticsCompany" v-if="completeForm.giftType === 'real'">
          <el-input v-model="completeForm.logisticsCompany" placeholder="请输入物流公司名称" />
        </el-form-item>

        <el-form-item label="快递单号" prop="logisticsNumber" v-if="completeForm.giftType === 'real'">
          <el-input v-model="completeForm.logisticsNumber" placeholder="请输入快递单号" />
        </el-form-item>

        <el-form-item label="备注">
          <el-input v-model="completeForm.remark" type="textarea" :rows="3" placeholder="请输入备注信息（可选）" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="completeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmComplete">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="兑换详情" width="800px">
      <div class="detail-content" v-if="detailData">
        <!-- 基本信息 -->
        <el-card class="detail-section" shadow="never">
          <template #header>
            <div class="card-header">
              <span>基本信息</span>
            </div>
          </template>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="兑换状态">
              <el-tag :type="getStatusTagType(detailData.status)">
                {{ getStatusText(detailData.status) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="兑换时间">
              {{ formatDateTime(detailData.createdTime) }}
            </el-descriptions-item>
            <el-descriptions-item label="完成时间" v-if="detailData.completedTime">
              {{ formatDateTime(detailData.completedTime) }}
            </el-descriptions-item>
            <el-descriptions-item label="备注" v-if="detailData.remark">
              {{ detailData.remark }}
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- 用户信息 -->
        <el-card class="detail-section" shadow="never">
          <template #header>
            <div class="card-header">
              <span>用户信息</span>
            </div>
          </template>
          <div class="user-info-detail">
            <el-avatar :size="60">
              {{ detailData.userName?.charAt(0) }}
            </el-avatar>
            <div class="user-details-detail">
              <div class="user-name-detail">{{ detailData.userName }}</div>
              <div class="user-id-detail">用户ID: {{ detailData.userId }}</div>
            </div>
          </div>
        </el-card>

        <!-- 礼品信息 -->
        <el-card class="detail-section" shadow="never">
          <template #header>
            <div class="card-header">
              <span>礼品信息</span>
            </div>
          </template>
          <div class="gift-info-detail">
            <el-image :src="detailData.giftImage" style="width: 100px; height: 100px; margin-right: 20px" fit="cover" :z-index="99999" preview-teleported :preview-src-list="[detailData.giftImage]" />
            <div class="gift-details-detail">
              <div class="gift-name-detail">{{ detailData.giftName }}</div>
              <div class="gift-type-detail">
                <el-tag :type="getGiftTypeTagType(detailData.giftType)" size="small">
                  {{ getGiftTypeText(detailData.giftType) }}
                </el-tag>
              </div>
              <div class="gift-quantity">数量: {{ detailData.quantity || 1 }}</div>
            </div>
          </div>
        </el-card>

        <!-- 费用信息 -->
        <el-card class="detail-section" shadow="never">
          <template #header>
            <div class="card-header">
              <span>费用信息</span>
            </div>
          </template>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="消耗金币">
              <span class="coin-text">{{ detailData.coins }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="补差金额" v-if="detailData.price > 0">
              <span class="amount-text">¥{{ detailData.price }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="补差金额" v-else>
              <span class="no-amount">-</span>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
  import { ref, reactive, onMounted, computed } from 'vue';
  import { useRouter } from 'vue-router';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import { getExchangeList, completeExchange, cancelExchange, exportExchangeList } from '@/api/gift';

  const router = useRouter();

  const list = ref([]);
  const total = ref(0);
  const listLoading = ref(true);
  const dateRange = ref([]);
  const completeDialogVisible = ref(false);
  const completeFormRef = ref();
  const completeForm = reactive({
    id: null,
    giftType: '',
    logisticsCompany: '',
    logisticsNumber: '',
    remark: ''
  });
  const cancelDialogVisible = ref(false);
  const cancelForm = reactive({
    id: null,
    reason: ''
  });
  const detailDialogVisible = ref(false);
  const detailData = ref({});

  // 完成兑换表单验证规则
  const completeRules = {
    logisticsCompany: [{ required: true, message: '请输入物流公司名称', trigger: 'blur' }],
    logisticsNumber: [{ required: true, message: '请输入快递单号', trigger: 'blur' }]
  };

  // 统计数据
  const statistics = ref({
    total: 0,
    pending: 0,
    completed: 0,
    cancelled: 0
  });

  const listQuery = reactive({
    pageIndex: 1,
    pageSize: 20,
    userName: '',
    giftName: '',
    giftType: '',
    status: '',
    startTime: '',
    endTime: ''
  });

  // 礼品类型映射
  const giftTypeMap = {
    vip: { text: 'VIP会员', type: 'success' },
    real: { text: '实物礼品', type: 'warning' },
    headwear: { text: '头饰装扮', type: 'info' }
  };

  // 状态映射
  const statusMap = {
    pending: { text: '待处理', type: 'warning' },
    completed: { text: '已完成', type: 'success' },
    cancelled: { text: '已取消', type: 'danger' }
  };

  // 获取礼品类型文本
  const getGiftTypeText = type => {
    return giftTypeMap[type]?.text || '未知';
  };

  // 获取礼品类型标签类型
  const getGiftTypeTagType = type => {
    return giftTypeMap[type]?.type || 'info';
  };

  // 获取状态文本
  const getStatusText = status => {
    return statusMap[status]?.text || '未知';
  };

  // 获取状态标签类型
  const getStatusTagType = status => {
    return statusMap[status]?.type || 'info';
  };

  // 格式化日期时间
  const formatDateTime = dateTime => {
    if (!dateTime) return '-';
    return new Date(dateTime).toLocaleString('zh-CN');
  };

  // 分页处理
  const handlePageChange = page => {
    listQuery.pageIndex = page;
    getList();
  };

  const handleSizeChange = size => {
    listQuery.pageSize = size;
    listQuery.pageIndex = 1;
    getList();
  };

  // 获取列表数据
  const getList = async () => {
    listLoading.value = true;
    try {
      const response = await getExchangeList(listQuery);
      if (response.code === 200) {
        list.value = response.data.list;
        total.value = response.data.total;
        statistics.value.total = response.data.total;
      }
    } catch (error) {
      console.error('获取兑换记录失败:', error);
      ElMessage.error('获取兑换记录失败');
    } finally {
      listLoading.value = false;
    }
  };

  // 日期范围处理
  const handleDateChange = dates => {
    if (dates && dates.length === 2) {
      listQuery.startTime = new Date(dates[0]).getTime();
      listQuery.endTime = new Date(dates[1]).getTime();
    } else {
      listQuery.startTime = '';
      listQuery.endTime = '';
    }
  };

  // 搜索筛选
  const handleFilter = () => {
    listQuery.pageIndex = 1;
    getList();
  };

  // 重置刷新
  const handleRefresh = () => {
    listQuery.pageIndex = 1;
    listQuery.pageSize = 20;
    listQuery.userName = '';
    listQuery.giftName = '';
    listQuery.giftType = '';
    listQuery.status = '';
    listQuery.startTime = '';
    listQuery.endTime = '';
    dateRange.value = [];
    selectedRows.value = [];
    getList();
  };

  // 选择行处理
  const handleSelectionChange = selection => {
    selectedRows.value = selection;
  };

  // 完成兑换
  const handleComplete = row => {
    completeForm.id = row._id;
    completeForm.giftType = row.giftType;
    completeForm.logisticsCompany = '';
    completeForm.logisticsNumber = '';
    completeForm.remark = '';
    completeDialogVisible.value = true;
  };

  // 确认完成兑换
  const confirmComplete = async () => {
    try {
      await completeFormRef.value.validate();

      const params = {
        id: completeForm.id,
        remark: completeForm.remark
      };

      // 如果是实物礼品，需要添加物流信息
      if (completeForm.giftType === 'real') {
        params.logisticsCompany = completeForm.logisticsCompany;
        params.logisticsNumber = completeForm.logisticsNumber;
      }
      console.log(3333, params);
      const response = await completeExchange(params);
      if (response.code === 200) {
        ElMessage.success('兑换完成成功');
        completeDialogVisible.value = false;
        getList();
      }
    } catch (error) {
      if (error !== 'cancel') {
        console.error('完成兑换失败:', error);
        ElMessage.error('完成兑换失败');
      }
    }
  };

  // 查看详情
  const handleDetail = row => {
    detailData.value = { ...row };
    detailDialogVisible.value = true;
  };

  // 导出数据
  const handleExport = async () => {
    try {
      ElMessage.info('正在导出数据，请稍候...');

      const response = await exportExchangeList(listQuery);

      // 创建下载链接
      const blob = new Blob([response], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      });
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `兑换记录_${new Date().toISOString().slice(0, 10)}.xlsx`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);

      ElMessage.success('导出成功');
    } catch (error) {
      console.error('导出失败:', error);
      ElMessage.error('导出失败');
    }
  };

  onMounted(() => {
    getList();
  });
</script>

<style scoped>
  .filter-container {
    margin-bottom: 20px;
  }

  .filter-form {
    margin-bottom: 0;
  }

  .stat-card {
    text-align: center;
  }

  .stat-content {
    padding: 20px 0;
  }

  .stat-number {
    font-size: 28px;
    font-weight: bold;
    color: #409eff;
  }

  .stat-number.pending {
    color: #e6a23c;
  }

  .stat-number.completed {
    color: #67c23a;
  }

  .stat-number.cancelled {
    color: #f56c6c;
  }

  .stat-label {
    margin-top: 8px;
    color: #606266;
    font-size: 14px;
  }

  .table-operations {
    margin-bottom: 15px;
  }

  .table-operations .el-button {
    margin-right: 10px;
  }

  .user-info {
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .user-avatar {
    margin-right: 12px;
  }

  .user-details {
    text-align: left;
  }

  .user-name {
    font-weight: bold;
    color: #303133;
    margin-bottom: 4px;
  }

  .user-id {
    font-size: 12px;
    color: #909399;
  }

  .gift-info {
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .gift-details {
    text-align: left;
  }

  .gift-name {
    font-weight: bold;
    color: #303133;
    margin-bottom: 4px;
  }

  .gift-type {
    margin-top: 4px;
  }

  .time-info {
    font-size: 13px;
    color: #606266;
  }

  .coin-text {
    color: #f56c6c;
    font-weight: bold;
  }

  .amount-text {
    color: #67c23a;
    font-weight: bold;
  }

  .no-amount {
    color: #909399;
  }

  .quantity-text {
    color: #409eff;
    font-weight: bold;
  }

  .order-number {
    font-family: 'Courier New', monospace;
    font-size: 12px;
    color: #606266;
  }

  .dialog-footer {
    text-align: right;
  }

  .detail-content {
    max-height: 600px;
    overflow-y: auto;
  }

  .detail-section {
    margin-bottom: 20px;
  }

  .detail-section:last-child {
    margin-bottom: 0;
  }

  .card-header {
    font-weight: 600;
    color: #303133;
  }

  .user-info-detail {
    display: flex;
    align-items: center;
  }

  .user-details-detail {
    margin-left: 20px;
  }

  .user-name-detail {
    font-size: 18px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 8px;
  }

  .user-id-detail {
    font-size: 14px;
    color: #909399;
  }

  .gift-info-detail {
    display: flex;
    align-items: center;
  }

  .gift-details-detail {
    flex: 1;
  }

  .gift-name-detail {
    font-size: 18px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 8px;
  }

  .gift-type-detail {
    margin-bottom: 8px;
  }

  .gift-quantity {
    font-size: 14px;
    color: #606266;
  }
</style>
